package com.xzh.mallorderapi.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzh.mallorderspi.model.Order;
import com.xzh.mallorderspi.model.search.OrderSeaechBean;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Mapper
public interface OrderMapper extends BaseMapper<Order> {

    @Select("SELECT COALESCE(SUM(total_pay), 0) FROM `order` WHERE DATE(checkout_time) BETWEEN #{startDate} AND #{endDate} AND is_del = 0")
    BigDecimal getTotalSales(@Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate);

    @Select("SELECT COUNT(*) FROM `order` WHERE DATE(checkout_time) BETWEEN #{startDate} AND #{endDate} AND is_del = 0")
    BigDecimal getTotalOrders(@Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate);

    @Select("SELECT COUNT(DISTINCT member_account) FROM `order` WHERE DATE(checkout_time) BETWEEN #{startDate} AND #{endDate} AND is_del = 0")
    BigDecimal getTotalCustomers(@Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate);

    @Select("SELECT pay_type as payType, COUNT(*) as count FROM `order` WHERE created_time BETWEEN #{startDate} AND #{endDate} GROUP BY pay_type")
    List<Map<String, Object>> getPayTypeStatistics(@Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate);


    Page<Order> findAll(@Param("osb") OrderSeaechBean osb, Page<Order> page);

    default Order findByOrderNo(String orderNo){
        LambdaQueryWrapper<Order> qw = Wrappers.lambdaQuery();
        qw.eq(Order::getOrderNo, orderNo);
        return selectOne(qw);
    }

    default Order findBySeckillNo(String seckillNo){
        LambdaQueryWrapper<Order> qw = Wrappers.lambdaQuery();
        qw.eq(Order::getSeckillNo, seckillNo);
        return selectOne(qw);
    }
}
